# 填充每个节点的下一个右侧节点指针

# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return root
        queue = [root]
        while len(queue):
            tmp = []
            for i in range(len(queue)):
                if queue[i].left:
                    tmp.append(queue[i].left)
                if queue[i].right:
                    tmp.append(queue[i].right)
                if i != 0:
                    queue[i-1].next = queue[i]
            queue = tmp
        return root


if __name__ == '__main__':
    so = Solution()

    # r = so.flatten(root)
    print(so)
